package com.tiger.admin.http.logs;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tiger.admin.Db;
import com.tiger.admin.SaveOperateLog;
import com.tiger.admin.dto.PaginationResult;
import com.tiger.admin.http.logs.dto.ExportTaskPageDto;
import com.tiger.common.UploadService;
import com.tiger.db.entity.Banner;
import com.tiger.db.entity.ExportTask;
import com.tiger.utils.ResponseUtil;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/exportTask")
public class ExportTaskController {
    private final Db db;

    private final UploadService uploadService;

    public ExportTaskController(Db db, UploadService uploadService) {
        this.db = db;
        this.uploadService = uploadService;
    }

    @PostMapping("page")
    public Object page(@RequestBody ExportTaskPageDto page, @RequestAttribute("memberId") long memberId) {
        PaginationResult<ExportTask> result = new PaginationResult<>();
        LambdaQueryWrapper<ExportTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(ExportTask::getId);

        wrapper.eq(ExportTask::getCreatorId, memberId);

        if(page.getStatus() != null) {
            wrapper.eq(ExportTask::getStatus, page.getStatus());
        }

        if(page.getType() != null) {
            wrapper.eq(ExportTask::getType, page.getType());
        }

        long total = db.exportTask.count(wrapper);

        if(total > 0) {
            result.setTotal(total);
            result.setRows(db.exportTask.list(wrapper));
        }

        return ResponseUtil.successRes(result);
    }


    @SaveOperateLog("删除导出记录")
    @PostMapping("delete/{id}")
    public Object del(@PathVariable long id, @RequestAttribute("memberId") long memberId) {
        ExportTask row = db.exportTask.getOne(new LambdaQueryWrapper<ExportTask>().select(ExportTask::getId, ExportTask::getUrl).eq(ExportTask::getId, id));
        if(row == null) return ResponseUtil.successRes();
        boolean r = db.exportTask.removeById(id);
        if(r) {
            uploadService.del(row.getUrl());
            return ResponseUtil.successRes();
        }
        return ResponseUtil.failRes();
    }


}
